# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Authentication object"""


class DzAuthenticate:

    def __init__(self,db,loginid,passwd):
        self.db = db
        self.loginid = loginid
        self.passwd = passwd
        self.status = 0
        self.tablename = 'dz_users'

    def __repr__(self):
        return str(self.__dict__)

    def __str__(self):
        return str(self.__dict__)

    def exec_SQL(self,cmd):
        curs = self.db.cursor()
        curs.execute(cmd)
        return curs

    def query(self,cmd):
        return self.db(cmd)

    def authenticate(self):
        query = "SELECT loginid, password, email, userid FROM %s WHERE loginid='%s' and password=OLD_PASSWORD('%s') and status='A'" \
            % (self.tablename,self.loginid,self.passwd)
        dataset = self.query(query)
        if len(dataset):
          rec = dataset[0]
          self.status = 1
          self.email = rec.EMAIL
          self.userid = rec.USERID
          self.loginid = rec.LOGINID
        else:
          self.status = 0
        return self.status

    def get_email(self):
        return self.email

if __name__ == '__main__':
    import unittest
    class AuthenticateTest(unittest.TestCase):
        def test(self):
            from zoom import zoomer
            auth = DzAuthenticate(zoomer.db,'dzguest','guest72P_d')
            self.assertEqual(auth.authenticate(),1)
            self.assertEqual(auth.get_email(),'guest@datazoomer.net')
            auth = DzAuthenticate(zoomer.db,'nouser','test')
            self.assertEqual(auth.authenticate(),0)
    unittest.main()
